package com.choosefine.it.basedata.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.choosefine.it.base.BaseController;
import com.choosefine.it.basedata.model.WorkType;
import com.choosefine.it.basedata.model.WorkTypeClass;
import com.choosefine.it.basedata.model.vo.WorkTypeFindVO;
import com.choosefine.it.basedata.model.vo.WorkTypeVO;
import com.choosefine.it.basedata.service.WorkTypeClassService;
import com.choosefine.it.basedata.service.WorkTypeService;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.utils.DateUtils;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/basedata/worktype")
@Api(value = "工种相关", description = "顾文伟")
public class WorkTypeController extends BaseController {
	Logger logger = LoggerFactory.getLogger(WorkTypeController.class);

	@Autowired
	WorkTypeService worktypeService;

	@Autowired
	WorkTypeClassService worktypeClassService;

	/**
	 * 添加工种类别
	 * 
	 * @param worktype
	 * @param response
	 * @return
	 * @throws BusinessException 
	 * @throws Exception
	 */
	@ApiOperation(value = "存储工种类别", notes = "", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiResponses({
			@ApiResponse(code = ResultCode.SUCCESS_CREATED, message = "添加成功返回结果"),
			@ApiResponse(code = ResultCode.FAILED, message = "请求参数错误") })
	@RequestMapping(method = RequestMethod.POST)
	public String save(@RequestBody WorkType worktype) throws BusinessException {
		String result;
		if (worktype != null) {
			worktype.setCtime(DateUtils.getNowTime());
			Integer num = worktypeService.insert(worktype);
			if (num > 0) {
				result = responseSuccess(num, ResultCode.SUCCESS_CREATED,
						ResultCode.MSG_CREATE_SUCCESS);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * 更新工种类型数据
	 * 
	 * @param worktype
	 *            类型名
	 * @return
	 * @throws BusinessException 
	 */
	@ApiOperation(value = "更改工种类型", notes = "")
	@ResponseBody
	@ApiResponses({
			@ApiResponse(code = ResultCode.SUCCESS_CREATED, message = "添加成功返回结果"),
			@ApiResponse(code = ResultCode.FAILED, message = "请求参数错误") })
	@RequestMapping(method = RequestMethod.PUT)
	public String update(@RequestBody WorkType worktype) throws BusinessException {
		String result = null;
		if (worktype != null) {
			worktype.setUtime(DateUtils.getNowTime());
			Integer num = worktypeService.update(worktype);
			if (num > 0) {
				result = responseSuccess(num, ResultCode.SUCCESS_CREATED,
						ResultCode.MSG_UPDATE_SUCCESS);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * 根据ID获取工种类型名
	 * 
	 * @param id
	 *            工种类型ID
	 * @return
	 */
	@ApiOperation(value = "根据ID取工种类别", notes = "")
	@ApiImplicitParam(name = "id", value = "工种类别ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String getWorkTypeById(@PathVariable Integer id) {
		String result = null;
		if (id != null) {
			WorkType worktype = worktypeService.findByPrimaryKey(id);
			if (worktype != null) {
				result = responseSuccess(worktype);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * 根据ID删除工种类型
	 * 
	 * @param id
	 *            工种类型ID
	 * @return
	 */
	@ApiOperation(value = "根据ID删除工种类别", notes = "")
	@ApiImplicitParam(name = "id", value = "工种ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable Integer id) {
		String result = null;
		if (id != null) {
			Integer num = worktypeService.deleteByPrimaryKey(id);
			if (num > 0) {
				result = responseSuccess(num);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;

	}

	@ApiOperation(value = "获取大类中工种类型", notes = "根据父类ID获取工种类型列表")
	@ApiImplicitParam(name = "father", value = "工种大类ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/worktypelistbyfather/{father}", method = RequestMethod.GET)
	public String getWorkTypeByFather(@PathVariable Integer father) throws BusinessException {
		String result = null;
		if (father != null) {
			List<WorkType> workTypeList = worktypeService.selectWorkTypeListByFather(father);
				result = responseArraySuccess(workTypeList);
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}
	@ApiOperation(value = "获取所有工种父类", notes = "")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pageNum", value = "起始行", required = true, dataType = "Integer", paramType = "path"),
		@ApiImplicitParam(name = "pageSize", value = "一页显示的行数", required = true, dataType = "Integer", paramType = "path") })
	@RequestMapping(value = "/worktypeclasslist/{pageNum}/{pageSize}", method = RequestMethod.GET)
	public String getWorkTypeClassList(@PathVariable Integer pageNum, @PathVariable Integer pageSize) throws BusinessException {
		String result = null;
		PageInfo<WorkTypeClass> worktypeclass = worktypeClassService.findAllByPage(null, pageNum, pageSize);
		if (worktypeclass != null) {
			result = responseArraySuccess(worktypeclass);
		} else {
			result = responseFail(ResultCode.MSG_ERROR);
		}
		return result;
	}

	@ApiOperation(value = "获取所有工种类别", notes = "")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pageNum", value = "起始行", required = true, dataType = "Integer", paramType = "path"),
		@ApiImplicitParam(name = "pageSize", value = "一页显示的行数", required = true, dataType = "Integer", paramType = "path") })
	@RequestMapping(value = "/worktypelist", method = RequestMethod.GET)
	public String getWorkTypeList(Integer pageNum, Integer pageSize) {
		String result = null;
		PageInfo<WorkType> worktype = worktypeService.findAllByPage(null, pageNum, pageSize);
		if (worktype != null) {
			result = responseArraySuccess(worktype);
		} else {
			result = responseFail(ResultCode.MSG_ERROR);
		}
		return result;
	}

	@ApiOperation(value = "根据名称获取工种", notes = "根据工种类别名和工种名获取工种")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "typeclassname", value = "工种类型名", dataType = "String", required = false, paramType = "query"),
			@ApiImplicitParam(name = "typename", value = "工种名", dataType = "String", required = false, paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "起始页", dataType = "Integer", required = true, paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页行", dataType = "Integer", required = true, paramType = "query") })
	@RequestMapping(value = "/worktypewithname", method = RequestMethod.GET)
	public String getWorkTypeWithName(String typeclassname, String typename,
			Integer pageNum, Integer pageSize) {
		String result = null;
		WorkTypeClass worktypeclass = null;
		Map<String, Object> map = new HashMap<>();
		if (typeclassname != null) {
			worktypeclass = worktypeClassService
					.getWorkTypeClassListByName(typeclassname);
		}
		PageInfo<WorkType> worktypelist;
		if (worktypeclass != null) {
			if (worktypeclass.getId() != null
					&& !"".equals(worktypeclass.getId())) {
				map.put("superId", worktypeclass.getId());
			}
			if (typename != null && !"".equals(typename)) {
				map.put("name", typename);
			}
			worktypelist = worktypeService.getWorkTypeListByName(map, pageNum,
					pageSize);
		} else if (typename != null) {
			if (typename != null && !"".equals(typename)) {
				map.put("name", typename);
			}
			worktypelist = worktypeService.getWorkTypeListByName(map, pageNum,
					pageSize);
		} else {
			worktypelist = worktypeService.findAllByPage(null, pageNum, pageSize);
		}
		if (worktypelist != null) {
			result = responseArraySuccess(worktypelist);
		} else {
			result = responseFail(ResultCode.MSG_ERROR);
		}
		return result;
	}

	@ApiIgnore
	@ApiOperation(value = "获取所有大类和工种类别", notes = "")
	@RequestMapping(value = "/workclassandtypelist", method = RequestMethod.GET)
	public String getWorkClassAndTypeList() {
		String result = null;
		List<WorkTypeVO> worktypevolist = null;
		List<WorkType> worktypelist = null;
		List<WorkTypeClass> worktypeclasslist = worktypeClassService.selectAll();
		if (worktypeclasslist != null) {
			worktypevolist = new ArrayList<WorkTypeVO>(worktypeclasslist.size());
			for (WorkTypeClass temp : worktypeclasslist) {
				WorkTypeVO worktypevo = new WorkTypeVO();
				worktypevo.setSuperid(temp.getId());
				worktypevo.setSupername(temp.getClassname());
				worktypelist = worktypeService.getWorkTypeListByFather(temp.getId());
				worktypevo.setList(worktypelist);
				worktypevolist.add(worktypevo);
			}
			result = responseArraySuccess(worktypevolist);
		} else {
			result = responseFail(ResultCode.MSG_ERROR);
		}
		return result;
	}
	@ApiOperation(value = "工种名称排序")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "fromId", value = "移动项", dataType = "Integer", required = true, paramType = "path"),
		@ApiImplicitParam(name = "toId", value = "移动到的位置", dataType = "Integer", required = true, paramType = "path"),
		@ApiImplicitParam(name = "order", value = "移动标识（1上移-1下移）", dataType = "Integer", required = true, paramType = "path")
	})
	@RequestMapping(value = "/workTypeOrder/{fromId}/{toId}/{order}", method = RequestMethod.PUT)
	public String workTypeOrder(@PathVariable Integer fromId, @PathVariable Integer toId, @PathVariable Integer order){
		String result = null;
		int num = 0;
		if(order>0){
			num += worktypeService.WorkTypeOrderUp(fromId, toId);
		}else{
			num += worktypeService.WorkTypeOrderDown(fromId, toId);
		}
		if(num>0){
			result = responseSuccess(num);
		}else{
			result = responseFail();
		}
		return result;
	}
	
	/**
	 * @Description：查询所有一级工种
	 * @Author：chenjian
	 * @Create Date：2017年2月17日
	 * @param：
	 * @return：
	 */
	@ApiOperation(value = "查询所有一级工种",response=WorkTypeFindVO.class)
	@RequestMapping(value = "/findWorkTypeList", method = RequestMethod.GET)
	public String findWorkTypeList(){
		String result = null;
		List<WorkTypeFindVO> list = worktypeService.findWorkTypeList();
		if(list!=null&&list.size()>0){
			result = responseSuccess(list);
		}else{
			result = responseFail();
		}
		return result;
	}
	/**
	 * @Description：根据一级工种id查询所有二级工种
	 * @Author：chenjian
	 * @Create Date：2017年2月17日
	 * @param：
	 * @return：
	 */
	@ApiOperation(value = "根据一级工种id查询所有二级工种",response=WorkTypeFindVO.class)
	@RequestMapping(value = "/findWorkTypeListBySuperId/{superId}", method = RequestMethod.GET)
	@ApiImplicitParam(name = "superId", value = "一级工程类型id", dataType = "int", required = true, paramType = "path")
	public String findWorkTypeListBySuperId(@PathVariable Integer superId){
		String result = null;
		List<WorkTypeFindVO> list = worktypeService.findWorkTypeListBySuperId(superId);
		if(list!=null&&list.size()>0){
			result = responseSuccess(list);
		}else{
			result = responseFail();
		}
		return result;
	}
}
